<template>
  <div ref="RefScrollBox" class="chat-box">
    <div ref="RefList" class="list-wrap">
      <CommentItem
        v-for="(item, index) in chatStore.commentList"
        :key="index"
        :commentInfo="item"
      />
    </div>

    <CommentInput />

    <transition name="router-change">
      <div v-if="showToBottom" class="new-tips" @click="toBottom()">
        <van-icon name="arrow-down" />
        <span>有新消息{{ arrivedState.bottom }}</span>
      </div>
    </transition>
  </div>
</template>

<script setup>
  import CommentInput from './CommentInput.vue'
  import CommentItem from './CommentItem.vue'
  import { useScroll, useElementSize } from '@vueuse/core'

  import { useChatStore } from '@/store/chat'
  const chatStore = useChatStore()

  const RefScrollBox = ref()
  const RefList = ref()

  const { y, arrivedState } = useScroll(RefScrollBox, { behavior: 'smooth' })
  const { height: boxHeight } = useElementSize(RefScrollBox, undefined, { box: 'border-box' })
  const { height: listHeight } = useElementSize(RefList, undefined, { box: 'border-box' })

  const maxScrollY = computed(() => listHeight.value - boxHeight.value + 1)

  const showToBottom = computed(
    () =>
      chatStore.hasNewComment &&
      !arrivedState.bottom &&
      listHeight.value > boxHeight.value &&
      y.value < maxScrollY.value
  )

  watch(arrivedState, val => {
    if (val) {
      chatStore.hasNewComment = false
    }
  })

  watch(maxScrollY, () => {
    if (!chatStore.hasNewMyComment) return
    nextTick(() => {
      toBottom()
      chatStore.hasNewMyComment = false
    })
  })

  const toBottom = () => {
    y.value = maxScrollY.value
  }
</script>

<style lang="less" scoped>
  .chat-box {
    width: 100%;
    height: 100%;
    overflow: hidden;
    overflow-y: auto;
  }
  .list-wrap {
    width: 100%;
    overflow: hidden;
    padding-bottom: 80px;
  }
  .new-tips {
    position: fixed;
    right: 20px;
    bottom: 102px;
    padding: 4px 8px;
    border-radius: 10px;
    font-size: 12px;
    color: var(--van-text-color);
    background: var(--van-primary-color);
  }
</style>
